package com.dts.evaluate.utils;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;

import com.dts.evaluate.APP;
import com.dts.evaluate.bean.EvaluateBean;
import com.dts.evaluate.bean.PersonBean;
import com.dts.evaluate.bean.PersonBroadBean;
import com.dts.evaluate.bean.SocketBean;
import com.dts.evaluate.bean.Worker;
import com.dts.evaluate.common.Constants;
import com.dts.evaluate.common.SocketType;
import com.dts.evaluate.service.CameraMediaRecordService;
import com.dts.evaluate.service.CameraPictureService;
import com.dts.evaluate.ui.activity.EvaluateActivity;
import com.dts.evaluate.ui.activity.NatureInfoSureActivity;
import com.dts.evaluate.ui.activity.OrganInfoSureActivity;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.util.Timer;
import java.util.TimerTask;

import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketHandler;
import de.tavendo.autobahn.WebSocketOptions;

/**
 * Created by user on 2016/7/1.
 */
public class SocketUtil {

    private static WebSocketConnection connection;
    private static SocketCallback mCallBack;
    private static Context mContext;
    //设备id
    private static String deviceId;

    private static Object lock = new Object();
    private static long preTime;
    private static WebSocketOptions webSocketOptions = new WebSocketOptions();

    private static Timer timer;


    /**
     *初始化SocketUtil,在application中调用
     */
    public static void init(final Context context){
        mContext = context;
        deviceId = IdUtil.getDeviceId(mContext);

        preTime = System.currentTimeMillis();
        webSocketOptions.setMaxMessagePayloadSize(3*1024*1024);
        try {
            if(connection != null){
                connection.disconnect();
                connection = null;
            }
            connection = new WebSocketConnection();

            connection.connect(Constants.SOCKET_URL,new WebSocketHandler(){
                @Override
                public void onOpen() {
                    super.onOpen();
                    LogUtil.v("connection----------------->onOpen");
                    register();
                    //在连接open之后，提交设备id,注册该socket连接
                }

                @Override
                public void onTextMessage(String payload) {
                    super.onTextMessage(payload);

                   LogUtil.v("payload:"+payload);

                    Gson gson = new Gson();

                    try {
                        SocketBean<JsonObject> socketBean = gson.fromJson(payload, new TypeToken<SocketBean<JsonObject>>() {
                        }.getType());
                        String type = socketBean.getType();
                        String callback = socketBean.getCallback();
                        JsonObject msg = socketBean.getMsg();

                        //开启录像功能
                        if(SocketType.CALL_BACK_START_VIDEO.equals(callback)){
                            String id = "";
                             boolean hasId =  msg.has("id");
                            if(hasId){
                                id =  msg.get("id").getAsString();
                            }
                            Intent intent = new Intent(context, CameraMediaRecordService.class);
                            intent.putExtra(Constants.VIDEO_TYPE,SocketType.CALL_BACK_START_VIDEO);
                            intent.putExtra(Constants.VIDEO_ID,id);
                            context.startService(intent);
                        }

                        //关闭录像功能
                        if(SocketType.CALL_BACK_STOP_VIDEO.equals(callback)){
                            Intent intent = new Intent(context, CameraMediaRecordService.class);
                            intent.putExtra(Constants.VIDEO_TYPE,SocketType.CALL_BACK_STOP_VIDEO);
                            context.startService(intent);
                        }

                        //注册成功主界面刷新广播
                        if(SocketType.CALL_BACK_INIT_MSG.equals(callback)){
                            Worker worker = gson.fromJson(msg,Worker.class);
                            APP.worker = worker;
                            Intent intent = new Intent();
                            intent.setAction(SocketType.CALL_BACK_INIT_MSG);
                            intent.putExtra(SocketType.CALL_BACK_INIT_MSG,worker);
                            context.sendBroadcast(intent);
                        }


                        //信息确认界面
                        if(SocketType.CALL_BACK_INFO_CONFIRM.equals(callback)){
                            //判断有没有信息确认页面打开,如果打开没有关闭,则不再进行打开该页面
                            if(!APP.sure_flag) {
                                APP.sure_flag = true;
                                PersonBean personBean = gson.fromJson(msg, PersonBean.class);
                                Intent intent;
                                String juridicalPersrson = personBean.getJuridicalPerson();
                                if (StringUtils.isEmpty(juridicalPersrson)) {
                                    intent = new Intent(context, NatureInfoSureActivity.class);
                                } else {
                                    intent = new Intent(context, OrganInfoSureActivity.class);
                                }
                                intent.putExtra(Constants.PERSON_BEAN, personBean);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                context.startActivity(intent);
                            }
                        }

                        //调用评价界面
                        if(SocketType.CALL_BACK_EVALUATE.equals(callback)){
                            LogUtil.v("eva_flag:"+APP.evaluate_flag);
                            if(!APP.evaluate_flag) {
                                APP.evaluate_flag = true;
                                EvaluateBean evaluateBean = gson.fromJson(msg, EvaluateBean.class);
                                Intent intent = new Intent(context, EvaluateActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intent.putExtra(Constants.EVALUATE_BEAN, evaluateBean);
                                context.startActivity(intent);
                            }
                        }

                        //调用评价结果
                        if(SocketType.CALL_BACK_EVALUATE_RESULT.equals(callback)){
                            if(mCallBack != null){
                                mCallBack.onSuccess(payload);
                                mCallBack = null;
                            }
                        }
                        //个人公告
                        if(SocketType.CALL_BACK_PERSON_BROAD.equals(callback)){
                            PersonBroadBean personBroadBean = gson.fromJson(msg,PersonBroadBean.class);
                            personBroadBean.setPcBroad(true);//设置为true，表示是pc端发布的个人公告
                            Intent intent = new Intent();
                            intent.setAction(SocketType.CALL_BACK_PERSON_BROAD);
                            intent.putExtra(Constants.PERSON_BROAD_BEAN,personBroadBean);
                            context.sendBroadcast(intent);
                            LogUtil.v("已发公告广播");
                        }

                        //拍照
                        if(SocketType.CALL_BACK_TAKE_PICTUREE.equals(callback)){
                            LogUtil.v("开始拍照---socketUtil------------>");
                            String projectid = "";
                            if(msg.has("projectid")){
                                projectid = msg.get("projectid").getAsString();
                            }
                            Intent intent = new Intent(context, CameraPictureService.class);
                            intent.putExtra(Constants.PROJECT_ID,projectid);
                            context.startService(intent);
                        }

                        //考勤
                        if(SocketType.CALL_BACK_ATTENDANCE.endsWith(callback)){
                                Intent intent = new Intent(SocketType.CALL_BACK_ATTENDANCE);
                            context.sendBroadcast(intent);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }


                }

                @Override
                public void onBinaryMessage(byte[] payload) {
                    super.onBinaryMessage(payload);
                }

                @Override
                public void onClose(int code, String reason) {
                    super.onClose(code, reason);
                    LogUtil.v("connection----------------->onClose  reason:"+reason);
                }
            },webSocketOptions);
        } catch (WebSocketException e) {
            e.printStackTrace();
            LogUtil.v("websocketConnection connect失败  error:"+e.getMessage());
        }

        //使用timer替代alarm发送定时心跳
        if(timer != null){
            try {
                timer.cancel();
                timer = null;
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                sendHeartMsg();
            }
        }, 2 * 1000, 5 * 1000);


        //设置心跳维持长连接
       /* if(!isAlarm) {
            LogUtil.v("设置alarm发送心跳");
            Intent intent = new Intent(mContext, KeepSocketHeartService.class);
             pendingIntent = PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
             alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
            Calendar calendar=Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 6*1000, pendingIntent);
            isAlarm = true;
        }*/
    }


    /**
     * 注册websocket连接,提交用户设备id
     */
    public static void register(){
        if(deviceId == null || "".equals(deviceId)){
            throw new IllegalArgumentException("SocketUtis is not init，SocketUtil没有初始化，需要在application中初始化");
        }
        if(!connection.isConnected()){
            LogUtil.v("websocketConnection 没有连接成功,注册失败");
            return;
        }
        //用gson构造注册json信息
        Gson gson = new Gson();
        SocketBean bean = new SocketBean();
        bean.setMine(deviceId);
        bean.setType(SocketType.TYPE_REGISTER);
        bean.setCallback(SocketType.CALL_BACK_INIT_MSG);
        String json = gson.toJson(bean);

        //提交注册信息到服务器
        try {
            synchronized (lock) {
                connection.sendTextMessage(json);
            }
        }catch (Exception e){
            e.printStackTrace();
            LogUtil.v("websocketConnection连接成功，但register失败：error:"+e.getMessage());

        }

    }


    /**
     * 断开连接
     */
    public static void disConnect(){
        if(timer != null){
            try {
                timer.cancel();
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        if(connection != null && connection.isConnected()){
            connection.disconnect();
        }
    }

    /**
     * 注册连接之后，可以使用该函数和服务器会话
     * @param msg  会话消息
     * @param socketCallback  会话回调用于接收服务器返回数据
     */
    public static void communicate(String msg,String type,String callback,@Nullable SocketCallback socketCallback){

        mCallBack = socketCallback;

        if(!connection.isConnected()){
            //throw new RuntimeException("websocketConnection is not connected,websocketConnection 没有连接成功");
            mCallBack.onError("websocketConnection没有连接，会话communicate失败");
            mCallBack = null;
            LogUtil.v("websocketConnection没有连接，会话communicate失败");
            return;
        }

        Gson gson = new Gson();
        SocketBean bean = new SocketBean();
        bean.setMine(deviceId);
        bean.setCallback(callback);
        bean.setType(type);
        bean.setMsg(msg);
        String json = gson.toJson(bean);

        try {
            synchronized (lock){
                connection.sendTextMessage(json);
                LogUtil.v("发送消息成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            LogUtil.v("websocketConnection连接成功，但是communicate失败"+e.getMessage());
            if(mCallBack != null){
                mCallBack.onError("websocketConnection连接成功，但是communicate失败"+e.getMessage());
                mCallBack = null;
            }
        }

    }

    /**
     * 发送心跳包，保持长连接
     */
    public static void sendHeartMsg(){
        LogUtil.v("sendHeartMsg");
        if(connection != null && !connection.isConnected()){
            connection = null;
            init(mContext);
        }
        try {
            synchronized (lock) {
                connection.sendTextMessage("\n\r");
            }
            //两次发送心跳的间隔时间
            long currentTime = System.currentTimeMillis();
            LogUtil.v("发送心跳,保持长连接  "+ (currentTime - preTime));
            preTime = currentTime;


        }catch (Exception e){
            e.printStackTrace();
            LogUtil.v("发送心跳，保持长连接失败 error:"+e.getMessage());
        }

    }



    public interface SocketCallback{
        void onSuccess(String payload);
        void onError(String error);
    }
}
